package com.example.voziloapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	public static final String URL = "http://10.0.2.2:8080/ProbaREST/korisno/Avozilo/Atest";
	//Declare the timer
	String voziloID="31";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		callWebService("qwe"); 
		final Button btn = (Button) findViewById(R.id.button1);
		final EditText tv = (EditText) findViewById(R.id.editText1);
		final GPSTracker gps = new GPSTracker(MainActivity.this);
		btn.setOnClickListener(new View.OnClickListener() {

		    public void onClick(View v) {
		        // TODO Auto-generated method stub
		    	btn.setEnabled(false);
		    	voziloID=tv.getText().toString();
		    	if(gps.canGetLocation()){
		             
		            double latitude = gps.getLatitude();
		            double longitude = gps.getLongitude();
		             
		            // \n is for new line
		            Log.d("LOKATOR", "Your Location is - \nLat: " + latitude + "\nLong: " + longitude);   
		        }else{
		            // can't get location
		            // GPS or Network is not enabled
		            // Ask user to enable GPS/network in settings
		            gps.showSettingsAlert();
		        }
		    }
		 });
		  
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
    public void callWebService(String q){  
         
        WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "Posting data...");
        wst.addNameValuePair("lat", q);
        
        Log.d("...",URL+" "+q);
        wst.execute(new String[] { URL+"?lat="+q });
          
        
    } // end callWebService()  
    public void handleResponse(String response) {
                
        try {
        	Log.d("RESPONSE",response);
             
        } catch (Exception e) {
            Log.e("BUG", e.getLocalizedMessage(), e);
        }
         
    }
public class WebServiceTask extends AsyncTask<String, Integer, String> {
	public static final int POST_TASK = 1;
    public static final int GET_TASK = 2;
     
    private static final String TAG = "WebServiceTask";

    // connection timeout, in milliseconds (waiting to connect)
    private static final int CONN_TIMEOUT = 3000;
     
    // socket timeout, in milliseconds (waiting for data)
    private static final int SOCKET_TIMEOUT = 5000;
     
    private int taskType = GET_TASK;
    private Context mContext = null;
    private String processMessage = "Processing...";

    private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

   // private ProgressDialog pDlg = null;
    public WebServiceTask(int taskType, Context mContext, String processMessage) {
    	 
        this.taskType = taskType;
        this.mContext = mContext;
        this.processMessage = processMessage;
    }
    public void addNameValuePair(String name, String value) {
    	 
        params.add(new BasicNameValuePair(name, value));
    }
    @Override
    protected void onPreExecute() {

    }
    protected String doInBackground(String... urls) {    
    String url = urls[0];
    String result = "";
    Log.d("Pozivam",urls[0]);
    HttpResponse response = doResponse(url);
    Log.d("Response:",Boolean.toString(response==null));
    if (response == null) {
        return result;
    } else {

        try {

            result = inputStreamToString(response.getEntity().getContent());
            Log.d("result:",result);
        } catch (IllegalStateException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);

        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

    }

    return result;
}
    @Override
    protected void onPostExecute(String response) {
         
        //handleResponse(response);
        
         
    }
     
    // Establish connection and socket (data retrieval) timeouts
    private HttpParams getHttpParams() {
         
        HttpParams htpp = new BasicHttpParams();
         
        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
         
        return htpp;
    }
    private HttpResponse doResponse(String url) {
        
        // Use our connection and data timeouts as parameters for our
        // DefaultHttpClient
        HttpClient httpclient = new DefaultHttpClient(getHttpParams());

        HttpResponse response = null;

        try {
        	switch (taskType) {
        
        
        case POST_TASK:
            HttpPost httppost = new HttpPost(url);
            // Add parameters
            httppost.setEntity(new UrlEncodedFormEntity(params));

            response = httpclient.execute(httppost);
            break;
        case GET_TASK:
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            break;
        }
    } catch (Exception e) {

        Log.e(TAG, e.getLocalizedMessage(), e);

    }

    return response;
}
 
private String inputStreamToString(InputStream is) {

    String line = "";
    StringBuilder total = new StringBuilder();

    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }

    // Return full string
    return total.toString();
}
}
private class GPSTracker extends Service implements LocationListener{
	  private final Context mContext;
	  
	    // flag for GPS status
	    boolean isGPSEnabled = false;
	 
	    // flag for network status
	    boolean isNetworkEnabled = false;
	 
	    boolean canGetLocation = false;
	 
	    Location location; // location
	    double latitude; // latitude
	    double longitude; // longitude
	 
	    // The minimum distance to change Updates in meters
	    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
	 
	    // The minimum time between updates in milliseconds
	    private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 1; // 1 minute
	 
	    // Declaring a Location Manager
	    protected LocationManager locationManager;
	 
	    public GPSTracker(Context context) {
	        this.mContext = context;
	        getLocation();
	    }
	    public Location getLocation() {
	        try {
	            locationManager = (LocationManager) mContext
	                    .getSystemService(LOCATION_SERVICE);
	 
	            // getting GPS status
	            isGPSEnabled = locationManager
	                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
	 
	            // getting network status
	            isNetworkEnabled = locationManager
	                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
	 
	            if (!isGPSEnabled && !isNetworkEnabled) {
	                // no network provider is enabled
	            } else {
	                this.canGetLocation = true;
	                // First get location from Network Provider
	                if (isNetworkEnabled) {
	                    locationManager.requestLocationUpdates(
	                            LocationManager.NETWORK_PROVIDER,
	                            MIN_TIME_BW_UPDATES,
	                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
	                    Log.d("Network", "Network");
	                    if (locationManager != null) {
	                        location = locationManager
	                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	                        if (location != null) {
	                            latitude = location.getLatitude();
	                            longitude = location.getLongitude();
	                        }
	                    }
	                }
	                // if GPS Enabled get lat/long using GPS Services
	                if (isGPSEnabled) {
	                    if (location == null) {
	                        locationManager.requestLocationUpdates(
	                                LocationManager.GPS_PROVIDER,
	                                MIN_TIME_BW_UPDATES,
	                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
	                        Log.d("GPS Enabled", "GPS Enabled");
	                        if (locationManager != null) {
	                            location = locationManager
	                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
	                            if (location != null) {
	                                latitude = location.getLatitude();
	                                longitude = location.getLongitude();
	                            }
	                        }
	                    }
	                }
	            }
	 
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	 
	        return location;
	    }
	    @Override
	    public void onLocationChanged(Location location) {
	    	latitude = location.getLatitude();
          longitude = location.getLongitude();
          Log.d("PROMJWNA",Double.toString(latitude)+" "+Double.toString(longitude));
          String q="?lat="+Double.toString(latitude)+"&long="+Double.toString(longitude)+"&id="+voziloID;  
          
          WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, MainActivity.this, "Posting data...");
          wst.addNameValuePair("lat", q);
          
          Log.d("...",MainActivity.URL+" "+q);
          wst.execute(new String[] { MainActivity.URL+q });
	    }
	 
	    @Override
	    public void onProviderDisabled(String provider) {
	    }
	 
	    @Override
	    public void onProviderEnabled(String provider) {
	    }
	 
	    @Override
	    public void onStatusChanged(String provider, int status, Bundle extras) {
	    }
	 
	    @Override
	    public IBinder onBind(Intent arg0) {
	        return null;
	    }
	    public double getLatitude(){
	        if(location != null){
	            latitude = location.getLatitude();
	        }
	         
	        // return latitude
	        return latitude;
	    }
	     
	    /**
	     * Function to get longitude
	     * */
	    public double getLongitude(){
	        if(location != null){
	            longitude = location.getLongitude();
	        }
	         
	        // return longitude
	        return longitude;
	    }
	    public boolean canGetLocation() {
	        return this.canGetLocation;
	    }
	     
	    /**
	     * Function to show settings alert dialog
	     * */
	    public void showSettingsAlert(){
	        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
	      
	        // Setting Dialog Title
	        alertDialog.setTitle("GPS is settings");
	  
	        // Setting Dialog Message
	        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
	  
	        // Setting Icon to Dialog
	        //alertDialog.setIcon(R.drawable.delete);
	  
	        // On pressing Settings button
	        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog,int which) {
	                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	                mContext.startActivity(intent);
	            }
	        });
	  
	        // on pressing cancel button
	        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	            dialog.cancel();
	            }
	        });
	  
	        // Showing Alert Message
	        alertDialog.show();
	    }
}
}




